package com.si.sea_island.controller;


import com.si.sea_island.base.JsonResult;
import com.si.sea_island.base.ResultCode;

import com.si.sea_island.mapper.IslandMapper;
import com.si.sea_island.mapper.ShopMapper;
import com.si.sea_island.mapper.UserDBMapper;
import com.si.sea_island.mapper.VerifyMapper;
import com.si.sea_island.pojo.UserDB;
import com.si.sea_island.pojo.VerifyDB;
import com.si.sea_island.pojo.game.*;
import io.swagger.annotations.*;

import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@Api(tags = "游戏模块")
public class GameController {

    @Autowired
    private VerifyMapper verifyMapper;
    @Autowired
    private UserDBMapper userDBMapper;
    @Autowired
    private IslandMapper islandMapper;
    @Autowired
    private ShopMapper shopMapper;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header")
    })
    @ApiOperation(value = "获取游戏数据",notes = "获取游戏数据")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/userInfo")
    public JsonResult getGameData(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"用户不存在");

        }

        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //获取id,铲子,珍珠,种子数量
        int id = userById.getId();
        String shovel = userById.getShovel();
        String pearl = userById.getPearl();
        String seed = userById.getSeed();


        ResultData resultData = new ResultData();
        //查询用户表的三个道具
        resultData.setPearl(pearl);
        resultData.setShovel(shovel);
        resultData.setSeed(seed);
        //查询海岛是否解锁
        List<Island> maps = islandMapper.getIslandList(id);
        List<Map<String,Object>> fruits = shopMapper.getFruitNameNum(id);
        resultData.setFruitNum(fruits);

        resultData.setMaps(maps);
        return JsonResult.success("获取成功").data(resultData);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "tId", value = "岛屿id", required = true, paramType = "param")
    })
    @ApiOperation(value = "解锁岛屿",notes = "解锁岛屿")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/unlock")
    @Transactional
    public JsonResult unlockIsland(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        Integer tId = Integer.parseInt(request.getParameter("tId"));
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否登录
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");

        }
        //查找岛屿是否存在
        Integer num = islandMapper.getIslandById(tId);
        if (num == null){
            return JsonResult.error(ResultCode.handle_fail,"岛屿不存在");
        }

        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //查询当前用户的铲子
        String shovel = userById.getShovel();
        //tid == 1 沙滩 需要消耗一把铲子
        if(tId == 1){
            //判断铲子是否足够
            if (!((new BigDecimal(shovel).subtract(new BigDecimal(1))).compareTo( BigDecimal.ZERO) >= 0)){
                //说明不足够
                return JsonResult.error(ResultCode.handle_fail,"铲子不足");
            }
            //铲子足够
            String newShovel = new BigDecimal(userById.getShovel()).subtract(new BigDecimal(1)).setScale(1, BigDecimal.ROUND_DOWN).toString();
            //将newShovel 更新到数据库
            userDBMapper.updateShovel(uid,newShovel);
            //获取当前时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastFetchTime = sdf.format(date);
            //用户岛屿中间表新增数据
            islandMapper.update(uid,tId,lastFetchTime);
            //在si_lands中插入数据
            islandMapper.insertLands(uid,tId,lastFetchTime);

            return JsonResult.success("解锁成功");
        }


        //tid为2,3,4,解锁需要消耗珍珠
        //查询当前用户珍珠
        String pearl = userById.getPearl();
        //查询当前解锁所需要的珍珠
        String needPearl = islandMapper.getIslandPrice(tId);
        //判断铲子是否足够
        if (!((new BigDecimal(pearl).subtract(new BigDecimal(needPearl))).compareTo(BigDecimal.ZERO) >= 0)){
            //说明不足够
            return JsonResult.error(ResultCode.handle_fail,"珍珠不足");
        }
        //说明珍珠足够
        //珍珠,种子bigDecimal 保留5位向上取整, 铲子是bigDecimal 保留1位向下取整
        String newPearl = new BigDecimal(userById.getPearl()).subtract(new BigDecimal(needPearl)).setScale(5, BigDecimal.ROUND_DOWN).toString();
        //将newShovel 更新到数据库
        userDBMapper.updatePearl(uid,newPearl);
        //用户岛屿中间表新增数据
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String lastFetchTime = sdf.format(date);
        islandMapper.update(uid,tId,lastFetchTime);
        //根据tid查找所对应的地图名
        String islandName = islandMapper.getIslandNameById(tId);
        //珍珠支出记录
        String operate = "解锁了" + islandName;
        String type = "0";
        userDBMapper.insertOperate(uid,needPearl,type,new Date(),pearl,operate);
        //在si_lands中插入数据
        islandMapper.insertLands(uid,tId,lastFetchTime);
        return JsonResult.success("解锁成功");
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header")
    })
    @ApiOperation(value = "加工厂加工",notes = "加工厂加工")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/factory")
    @Transactional
    public JsonResult factoryProcessing(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");

        }
        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //判断当前product是否为0
        if (userById.getProductFruit().equals("0")){
            return JsonResult.error(ResultCode.handle_fail,"果实不足");
        }
        String productFruit = userById.getProductFruit();
        //获得当前数量
        String pearl = userById.getPearl();
        String seed= userById.getSeed();
        //加工厂加工获得的
        BigDecimal productPearl = new BigDecimal(productFruit).multiply(new BigDecimal("0.9"));
        BigDecimal productSeed = new BigDecimal(productFruit).multiply(new BigDecimal("0.001"));

        //获得的珍珠和奇异种子
        String newPearl = new BigDecimal(pearl).add(productPearl).setScale(5, BigDecimal.ROUND_UP).toString();
        String newSeed = new BigDecimal(seed).add(productSeed).setScale(5, BigDecimal.ROUND_UP).toString();

        String newProductFruit = "0";
        //更新数据
        userDBMapper.updateProduct(newPearl,newSeed,newProductFruit,uid);
        //收益支出表中插入数据
        String operate = "加工了" + productFruit + "个果实";
        String type = "1";
        String product = productPearl.setScale(5, BigDecimal.ROUND_UP).toString();
        userDBMapper.insertOperate(uid,product,type,new Date(),pearl,operate);

        return JsonResult.success("加工成功");
    }

    /**
     * 种植
     * @param request
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "number", value = "种植数量", required = true, paramType = "param")
    })
    @ApiOperation(value = "种植",notes = "种植")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/plant")
    public JsonResult plant(HttpServletRequest request ){
        //获取number
        String number = request.getParameter("number");
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");

        }
        //判断number是否为空
        if(number.equals("0") || number == null){
            return JsonResult.error(ResultCode.handle_fail,"种植数量不能为0");
        }

        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //获取种子数量
        String seed = userById.getSeed();
        //判断种子是否足够
        if (!((new BigDecimal(seed).subtract(new BigDecimal(number))).compareTo( BigDecimal.ZERO) >= 0)){
            //说明不足够
            return JsonResult.error(ResultCode.handle_fail,"种子不足");
        }
        //种子,bigDecimal 保留5位向上取整
        String newSeed = new BigDecimal(seed).subtract(new BigDecimal(number)).setScale(5, BigDecimal.ROUND_UP).toString();
        //将newSeed 更新到数据库
        userDBMapper.updateSeed(newSeed,uid);
        //种植后获得果实
        List<Integer> randomFruitNum = getRandomFruitNum(Integer.parseInt(number));
        //更新数据
        for (int i = 0; i < randomFruitNum.size(); i++) {
            shopMapper.updateFruit(uid,i+1,randomFruitNum.get(i));
        }
        return JsonResult.success("种植成功");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "number", value = "购买数量", required = true, paramType = "param"),
            @ApiImplicitParam(name = "id", value = "食物id", required = true, paramType = "param")
    })
    @ApiOperation(value = "购买食物",notes = "购买食物")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/buy")
    @Transactional
    public JsonResult buyFoot(HttpServletRequest request ){
        //获取token
        String token = request.getHeader("token");
        Integer id = Integer.parseInt(request.getParameter("id"));
        String number = request.getParameter("number");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");

        }
        //获取用户id
        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //判断食物id是否存在
        Integer num = shopMapper.getFoodById(id);
        if(num == null){
            //不存在
            return JsonResult.error(ResultCode.handle_fail,"食物不存在");
        }
        if (number.equals("0") || number == null){
            return JsonResult.error(ResultCode.handle_fail,"购买数量不能为0");
        }
        //查询当前购买道具的价格
        Double price = shopMapper.getShopById(id);
        //计算总价格
        price = price * Integer.parseInt(number);
        //判断珍珠是否足够
        if (!((new BigDecimal(userById.getPearl()).subtract(new BigDecimal(price))).compareTo( BigDecimal.ZERO) >= 0)){
            //说明不足够
            return JsonResult.error(ResultCode.handle_fail,"珍珠不足");
        }
        //珍珠,种子bigDecimal 保留5位向上取整, 铲子是bigDecimal 保留1位向下取整
        //用户当前珍珠数量
        String pearl = userById.getPearl();
        String newPearl = new BigDecimal(pearl).subtract(new BigDecimal(price)).setScale(5, BigDecimal.ROUND_UP).toString();
        //将newPearl 更新到数据库
        userDBMapper.updatePearl(uid,newPearl);
        //更新用户食物数量
        userDBMapper.updateFood(id,number,uid);
        //查询食物名称
        String name = shopMapper.selectFoodName(id);
        //收入支出插入数据
        String operate = "购买了" + number + "个"+name;
        String type = "0";
        String spend = new BigDecimal(price).setScale(5, BigDecimal.ROUND_UP).toString();
        userDBMapper.insertOperate(uid,spend,type,new Date(),pearl,operate);
        return JsonResult.success("购买食物成功");
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "number", value = "出售数量", required = true, paramType = "param"),
            @ApiImplicitParam(name = "id", value = "果实id", required = true, paramType = "param")
    })
    @ApiOperation(value = "出售果实",notes = "出售果实")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    /**
     * 出售果实
     * @param request
     * @param number 出售数量
     * @param id  果实id
     * @return
     */

    @PostMapping("/api/sell")
    @Transactional
    public JsonResult sellFruit(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");

        Integer id = Integer.parseInt(request.getParameter("id"));

        String number = request.getParameter("number");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        //获取用户id
        int uid = verifyDBByToken.getUid();
        //根据uid查询
        UserDB userById = userDBMapper.getUserById(uid);
        //查询果实id是否存在
        Integer count = shopMapper.getFruitById(id);
        if(count == null){
            return JsonResult.error(ResultCode.handle_fail,"果实不存在");
        }
        if (number.equals("0")){
            return JsonResult.error(ResultCode.handle_fail,"出售数量不能为0");
        }
        //获取当前果实数量
        String num = shopMapper.getFruitNum(uid,id);

        if (!((new BigDecimal(num).subtract(new BigDecimal(number))).compareTo( BigDecimal.ZERO) > 0)){
            //说明不足够
            return JsonResult.error(ResultCode.handle_fail,"该果实数量不足");
        }

        //足够 查询当前果实对应的价格
        Double price = shopMapper.getFruitPrice(id);
        // 计算出售所得的总价格
        price = price * Integer.parseInt(number);
        //更新果实数量
        shopMapper.updateFruitNum(uid,id,number);
        //更新珍珠数量
        String pearl = userById.getPearl();
        pearl = new BigDecimal(pearl).add(new BigDecimal(price)).setScale(5,BigDecimal.ROUND_UP).toString();
        userDBMapper.updatePearl(uid,pearl);
        //收益支出表中插入数据
        //获取出售果实的name
        String name = shopMapper.getFruitByName(id);
        String operate = "出售了" + number +"个"+name;
        String type = "1";
        String fetch = new BigDecimal(price).setScale(5, BigDecimal.ROUND_UP).toString();
        userDBMapper.insertOperate(uid,fetch,type,new Date(),pearl,operate);
        return JsonResult.success("出售成功");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "page", value = "页码", required = true, paramType = "param"),
            @ApiImplicitParam(name = "size", value = "每页数量", required = true, paramType = "param")
    })
    @ApiOperation(value = "获取用户列表",notes = "获取用户列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    /**
     * 获取用户列表
     * @param request
     * @return
     */
    @GetMapping("/api/list")
    public JsonResult getList(HttpServletRequest request ){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        //获取页码和数量
        String pageStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");

        int page = 1;
        int size = 20;

        try {
            page = Integer.parseInt(pageStr);
            size = Integer.parseInt(sizeStr);
        } catch (NumberFormatException e) {
            // 如果无法转换，使用默认值
            page = 1;
            size = 20;
        }
        page = (page -1)*size;
        List<UserDB> list = userDBMapper.selectList(page,size);
        List<User> userList = new ArrayList<>();
        for (UserDB user : list) {
            userList.add(new User(user.getId(), user.getNickName(), user.getAvatar()));
        }
        return JsonResult.success("获取用户列表").data(userList);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "type", value = "转换类型 0:珍珠，1：铲子，2:奇异种子", required = true, paramType = "param"),
            @ApiImplicitParam(name = "number", value = "数量", required = true, paramType = "param"),
            @ApiImplicitParam(name = "password", value = "支付密码",required = true, paramType = "param"),
            @ApiImplicitParam(name = "id", value = "目标用户手机号", required = true, paramType = "param")
    })
    @ApiOperation(value = "金锭转换",notes = "金锭转换")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    /**
     * 金锭转换（已完成）
     * @param request 获取请求头   收取手续费5%
     * @param type 转换类型 0:珍珠，1：铲子，2:奇异种子
     * @param number 数量
     * @param password 支付密码
     * @param id 目标用户手机号
     * @return
     */
    @PostMapping("/api/give")
    @Transactional
    public JsonResult give(HttpServletRequest request){
        // 获取token
        String token = request.getHeader("token");
        // 根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        // 判断当前用户是否存在
        if (verifyDBByToken == null) {
            return JsonResult.error(ResultCode.user_not_find, "请登录");
        }

        int uid = verifyDBByToken.getUid();
        UserDB userById = userDBMapper.getUserById(uid);

        // 从请求头中获取type、number、password和id
        String typeStr = request.getParameter("type");
        String numberStr = request.getParameter("number");
        String password = request.getParameter("password");
        String id = request.getParameter("id");

        // 判断密码是否正确
        if (!password.equals(userById.getPayPassword())) {
            return JsonResult.error(ResultCode.handle_fail, "交易密码错误");
        }

        // 交易密码正确
        // 查询目标用户是否存在
        UserDB user = userDBMapper.selectUserByUsername(id);
        if (user == null) {
            return JsonResult.error(ResultCode.user_not_find, "目标用户不存在");
        }

        if (numberStr.matches("^[a-zA-Z]+$")) {
            return JsonResult.error(ResultCode.handle_fail, "数量必须是数字");
        } else if (numberStr.matches("^[\u4e00 - \u9fa5]+$")) {
            return JsonResult.error(ResultCode.handle_fail, "数量必须是数字");
        }

        // 判断number是否为数字
        int number;
        try {
            number = Integer.parseInt(numberStr);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.handle_fail, "数量必须是有效数字");
        }

        if (number <= 0) {
            return JsonResult.error(ResultCode.handle_fail, "数量必须大于0");
        }

        int type;
        try {
            type = Integer.parseInt(typeStr);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.handle_fail, "转换类型必须是有效数字");
        }

        if (type == 0) {
            // 珍珠
            if (!((new BigDecimal(userById.getPearl()).subtract(new BigDecimal(number))).compareTo(BigDecimal.ZERO) >= 0)) {
                return JsonResult.error(ResultCode.handle_fail, "珍珠不足");
            }

            // 当前用户珍珠数量减少
            String pearlById = userById.getPearl();
            String oldPearl = new BigDecimal(userById.getPearl()).setScale(5, BigDecimal.ROUND_UP).toString();

            String newPearl = new BigDecimal(userById.getPearl()).subtract(new BigDecimal(number)).setScale(5, BigDecimal.ROUND_UP).toString();
            userDBMapper.updatePearl(uid, newPearl);
            // 目标用户珍珠数量增加
            UserDB userDB = userDBMapper.selectUserByUsername(id);

            String pearl = new BigDecimal(userDB.getPearl()).add(new BigDecimal(number)).setScale(5, BigDecimal.ROUND_UP).toString();
            userDBMapper.updatePearl(userDB.getId(), pearl);
            // 收益支出表中插入数据
            // 1.目标用户收入
            String operate = "来自用户" + userById.getNickName() + "的" + number + "个珍珠";
            String type1 = "1";
            String fetch = new BigDecimal(number).setScale(5, BigDecimal.ROUND_UP).toString();
            // 目标用户之前珍珠数量
            String pearl1 = userDB.getPearl();
            userDBMapper.insertOperate(userDB.getId(), fetch, type1, new Date(), pearl1, operate);
            // 2.当前用户支出
            String operate1 = "赠送给了用户" + userDB.getNickName() + "  " + number + "个珍珠";
            String type2 = "0";
            // 当前用户之前珍珠数量
            userDBMapper.insertOperate(uid, fetch, type2, new Date(), oldPearl, operate1);
            UserDB userId = userDBMapper.getUserById(uid);
            // 扣除手续费 5%
            // premium手续费
            // 扣除转出去剩下的珍珠nowPearl
            String nowPearl = userId.getPearl();
            String premium = new BigDecimal(number).multiply(new BigDecimal("0.05")).setScale(5, BigDecimal.ROUND_UP).toString();
            String uidNewPearl = new BigDecimal(nowPearl).subtract(new BigDecimal(premium)).setScale(5, BigDecimal.ROUND_UP).toString();
            // 当前用户修改扣除手续费
            userDBMapper.updatePearl(uid, uidNewPearl);
            // 支出
            String operate2 = "赠送给了用户" + userDB.getNickName() + "  " + number + "个珍珠的手续费为" + premium;
            userDBMapper.insertOperate(uid, premium, type2, new Date(), nowPearl, operate2);
        } else {
            // 铲子
            if (!((new BigDecimal(userById.getShovel()).subtract(new BigDecimal(number))).compareTo(BigDecimal.ZERO) >= 0)) {
                return JsonResult.error(ResultCode.handle_fail, "铲子不足");
            }

            // 当前用户铲子数量减少
            String newShovel = new BigDecimal(userById.getShovel()).subtract(new BigDecimal(number)).setScale(1, BigDecimal.ROUND_UP).toString();
            userDBMapper.updateShovel(uid, newShovel);
            // 目标用户铲子数量增加
            UserDB userDB = userDBMapper.selectUserByUsername(id);
            String shovel = new BigDecimal(userDB.getShovel()).add(new BigDecimal(number)).setScale(1, BigDecimal.ROUND_UP).toString();
            userDBMapper.updateShovel(userDB.getId(), shovel);
        }

        return JsonResult.success("互转成功");
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "tid", value = "岛屿id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "index", value = "土地索引", required = true, dataType = "int"),
            @ApiImplicitParam(name = "fld", value = "果实id", required = true, dataType = "int")

    })
    @ApiOperation(value = "获取岛屿数据",notes = "获取岛屿数据")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    /**
     * 获取岛屿数据
     * @param request 获取请求头
     * @return
     */
    @PostMapping("/api/game/islandInfo")
    @Transactional
    public JsonResult landInfo(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        int uid = verifyDBByToken.getUid();
        UserDB userById = userDBMapper.getUserById(uid);
        //用户id
        int id = userById.getId();
        // 从请求头中获取tid
        String tidHeader = request.getParameter("tid");
        if (tidHeader == null) {
            return JsonResult.error(ResultCode.param_is_null, "请求头中未包含tid");
        }
        Integer tid;
        try {
            tid = Integer.parseInt(tidHeader);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.param_is_null, "tid格式不正确");
        }
        //岛屿是否解锁
        Integer island = islandMapper.getIslandId(tid,id);
        //岛屿未解锁
        if (island == null || island == 0){
            return JsonResult.error(ResultCode.handle_fail,"岛屿未解锁");
        }
        //

        Result land = islandMapper.getlands(tid,id);
        //岛屿，土地，果实
        Integer tld = land.getTid();
        Integer index1 = land.getIndex();
        Integer fld = land.getFld();
        //封装一个map集合将上述数据封装到集合中
        List<Result> list = new ArrayList<>();
        Result result = new Result();


        //判断是否种植种子
        if (fld == 0 || fld == null){
            long number = 0L;
            String str = String.valueOf(number);
            result.setFld(fld);
            result.setIndex(index1);
            result.setTid(tld);
            result.setDownTime(str);
            list.add(result);
            return JsonResult.success("种子未种植").data(list);
        }else {
            // 获取当前时间
            Date currentDate = new Date();
            //种植时间
            String downTimeStr  = land.getDownTime();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date downTime = null;
            try {
                downTime = sdf.parse(downTimeStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 当前时间减去数据库中的种植时间
            long currentTime = currentDate.getTime();
            long databaseTime = downTime.getTime();
            // 当前时间减去数据库中的种植时间
            long difference = currentTime - databaseTime;
            // 将毫秒数转换为秒
            long differenceInSeconds = difference / 1000;
            String differenceStr = String.valueOf(differenceInSeconds);
            //判断其是否小于86400秒并且fld=0的情况下
            if (differenceInSeconds < 86400 && fld == 0){
                long number = 0L;
                String str = String.valueOf(number);
                //返回前端数据修改为0
                result.setFld(fld);
                result.setIndex(index1);
                result.setTid(tld);
                result.setDownTime(str);
                list.add(result);
                return JsonResult.success("种子未种植").data(list);
            }else if (differenceInSeconds >= 86400){
                long number = 86400L;
                String str = String.valueOf(number);
                //果实成熟
                result.setFld(fld);
                result.setIndex(index1);
                result.setTid(tld);
                result.setDownTime(str);
                list.add(result);
                return JsonResult.success("果实已成熟").data(list);
            }else if (differenceInSeconds < 86400 && fld == 1){
                //果实为成熟
                result.setFld(fld);
                result.setIndex(index1);
                result.setTid(tld);
                result.setDownTime(differenceStr);
                list.add(result);
                return JsonResult.success("果实未成熟").data(list);
            }
            //封装一个map集合将上述数据封装到集合中
            result.setFld(fld);
            result.setIndex(index1);
            result.setTid(tld);
            result.setDownTime(differenceStr);
            list.add(result);
            return JsonResult.success("查询成功").data(list);
        }

    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "tid", value = "岛屿id", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "index", value = "土地id", required = true, dataType = "Integer")
    })
    @ApiOperation(value = "岛屿土地种植",notes = "岛屿土地种植")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    //土地种植
    @PostMapping("/api/game/plant")
    @Transactional
    public JsonResult fldplant(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        int uid = verifyDBByToken.getUid();
        UserDB userById = userDBMapper.getUserById(uid);
        //用户id
        int id = userById.getId();
        // 从请求头中获取tid
        String tidHeader = request.getParameter("tid");
        if (tidHeader == null) {
            return JsonResult.error(ResultCode.param_is_null, "请求头中未包含tid");
        }
        Integer tid;
        try {
            tid = Integer.parseInt(tidHeader);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.param_is_null, "tid格式不正确");
        }

        // 从请求头中获取index
        String indexHeader = request.getParameter("index");
        if (indexHeader == null) {
            return JsonResult.error(ResultCode.param_is_null, "请求头中未包含index");
        }
        Integer index;
        try {
            index = Integer.parseInt(indexHeader);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.param_is_null, "index格式不正确");
        }

        //岛屿是否解锁
        List<Island> island = islandMapper.getIslandList(id);
        //岛屿未解锁
        if (island == null){
            return JsonResult.error(ResultCode.handle_fail,"岛屿未解锁");
        }
        //判断土地id
        Lands lands = islandMapper.getland(tid,id);
        if (lands == null) {
            return JsonResult.error(ResultCode.handle_fail, "土地不存在");
        }
        //判断是否种植种子
        Integer fld1 = lands.getFld();
        if (fld1 != 0 && fld1 != null){
            return JsonResult.error(ResultCode.handle_fail,"土地已种植");
        }
        //种植种子
        if (fld1 == 0){
            //修改数据库中种子id为一
            fld1 = 1;
            islandMapper.updatePlant(tid,fld1,id,index);
        }

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String beijingTime = sdf.format(date);
        //修改数据库中时间
        islandMapper.updateTime(tid,beijingTime,id,index);
        return JsonResult.success("种植成功");
    }



    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken", value = "是否充值认证令牌", required = true, paramType = "header"),
            @ApiImplicitParam(name = "tid", value = "岛屿ID", required = true, paramType = "param")
    })
    @ApiOperation(value = "岛屿产出领取",notes = "岛屿产出领取")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    /**
     * 岛屿产出领取(未完成)
     * @param request
     * @param tid
     * @return
     */
    @PostMapping("/api/game/gain")
    @Transactional
    public JsonResult fetch(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        int uid = verifyDBByToken.getUid();
        UserDB userById = userDBMapper.getUserById(uid);
        //用户id
        int id = userById.getId();
        // 从请求头中获取tid
        String tidHeader = request.getParameter("tid");
        if (tidHeader == null) {
            return JsonResult.error(ResultCode.param_is_null, "请求头中未包含tid");
        }
        Integer tid;
        try {
            tid = Integer.parseInt(tidHeader);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.param_is_null, "tid格式不正确");
        }

        // 从请求头中获取index
        String indexHeader = request.getParameter("index");
        if (indexHeader == null) {
            return JsonResult.error(ResultCode.param_is_null, "请求头中未包含index");
        }
        Integer index;
        try {
            index = Integer.parseInt(indexHeader);
        } catch (NumberFormatException e) {
            return JsonResult.error(ResultCode.param_is_null, "index格式不正确");
        }
        //判断土地id
        Lands lands = islandMapper.getland(tid,id);
        if (lands == null) {
            return JsonResult.error(ResultCode.handle_fail, "土地不存在");
        }

        //获取当前时间
        Date date = new Date();
        //获取算出果实成熟时间
        //当前时间减去数据库中的种植时间
        long currentTime = date.getTime();
        //获取数据库中的时间
        String time = lands.getDownTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Date beijingTime = null;
        try {
            beijingTime = sdf.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        long databaseTime = beijingTime.getTime();
        //当前时间减去数据库中的种植时间
        long difference = currentTime - databaseTime;
        if (difference < 86400000 ){
            return JsonResult.error(ResultCode.handle_fail,"果实未成熟");
        }else{
            //果实成熟，果实数量增加
            //获取用户当前果实数量
            UserDB userDB = userDBMapper.getUserById(id);
            String productFruit = userDB.getProductFruit();
            //果实数量增加,果实数量最多为9，超过9则不增加
            String newFruit = new BigDecimal(productFruit).add(new BigDecimal("9")).setScale(1,BigDecimal.ROUND_UP).toString();

            //修改数据库中果实数量
            userDBMapper.updateFruit(id,newFruit);
        }
        //获得当时时间将当前时间修改到数据库
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String beijingTime1 = sdf1.format(date);

        //修改数据库中时间
        islandMapper.updateTime(tid,beijingTime1,id,index);
        //果实成熟后，果实数量增加，种子id修改为0
        Integer fld = lands.getFld();
        if (fld == 1){
            //修改数据库中种子id为0
            islandMapper.updatePlant(tid,0,id,index);
        }
        return JsonResult.success("获取成功");

    }

    /**
     * 我的收益记录(完成)
     * @param request
     * @return
     */
    @PostMapping("/api/earnings")
    public JsonResult myEarnings(HttpServletRequest request,@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "20") int size){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        int uid = verifyDBByToken.getUid();
        String type = "1";
        //分页查询
        List<OperateEarnings> list =  userDBMapper.selectOperate((page-1)*size,type,size,uid);
        return JsonResult.success("查询成功").data(list);
    }

    /**
     * 我的支出记录(完成)
     * @param request
     * @return
     */
    @PostMapping("/api/expenditures")
    public JsonResult myExpenditures(HttpServletRequest request,@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "20") int size){
        //获取token
        String token = request.getHeader("token");
        //根据token查找当前用户
        VerifyDB verifyDBByToken = verifyMapper.getVerifyDBByToken(token);
        //判断当前用户是否存在
        if (verifyDBByToken == null){
            return JsonResult.error(ResultCode.user_not_find,"请登录");
        }
        int uid = verifyDBByToken.getUid();
        String type = "0";
        //分页查询
        List<OperateExpenditures> list = userDBMapper.selectOperateExpenditures((page-1)*size,type,size,uid);
        return JsonResult.success("支出记录").data(list);
    }


    //随机果实
    public int randomFruit(){
        Random random = new Random();
        //果实概率
        double fruitProbability = random.nextDouble();

        if (fruitProbability < 0.6) {
            return 1;
        } else if (fruitProbability < 0.86) {
            return 2;
        } else if (fruitProbability < 0.96) {
            return 3;
        } else if (fruitProbability < 0.99) {
            return 4;
        } else {
            return 5;
        }
    }

    //根据传入的数量来获取随机果实的数量
    public List<Integer> getRandomFruitNum(int num){
        List<Integer> list = new ArrayList<>(Collections.nCopies(5, 0));

        for (int i = 0; i < num; i++) {
            int fruitNum = randomFruit(); //1,2,3,4,5
            list.set(fruitNum-1,list.get(fruitNum-1) + 1);
        }

        return list;
    }

}
